import React, { Component, Fragment } from "react";
import { connect } from "react-redux";
import MainLayout from "../../../../component/mainLayout/mainLayout";
import { BillTableCell } from "../../../../component/billTableCell/BillTableCell";
import { getAppPlatformsDatas } from "../../../../Redux/Action/nativeDatas/nativeDatas";
import {
	BillDetailData,
	BillListData,
	BillHomeData
} from "../../../../Redux/Action/bill/billAction";
import "./index.scss";
import Banner from "@/views/viewCommon/Banner";
import { InterfaceG } from "@config/Config";
import { setUserType } from "../../../../Redux/Action/credit/AuthenticationA";
import { getLoanData } from "../../../../Redux/Action/loanProcess/loanprocess";
import yhTools from "../../../../tools/yh";
import xhfConfig from "../../../../config/XHFConfig";
import { Toast, Modal } from "antd-mobile";
const modalAlert = Modal.alert;
import questionLine from "@images/imageXHF/question-line.png";
import QueryString from "qs";

function closest(el, selector) {
	const matchesSelector =
		el.matches ||
		el.webkitMatchesSelector ||
		el.mozMatchesSelector ||
		el.msMatchesSelector;
	while (el) {
		if (matchesSelector.call(el, selector)) {
			return el;
		}
		el = el.parentElement;
	}
	return null;
}

class BillHomePage extends Component {
	constructor(props) {
		super(props);
		this.state = {
			tabIndex: 0,
			modal1: false,
			pageData: {
				billMonth: "",
				billAmount: "", // 账单金额
				billDate: "", // 账单日
				rtnDate: "", // 还款日
				billNo: "", // 账单编号
				billStatus: "", // 0-未出账 1-已出账 2-已结清 3-无需还款 4-逾期
				billStatusName: "",
				isOverdue: "", // 0-无逾期，1-已逾期
				rtnBtnShow: "", // false-不显示还款按钮，true-显示还款按钮
				isOverdueName: "",
				rtnStatus: "", //是否还款日
				transactionList: [],
				onHalfAngle: "0.00",
				isLoaded: false, //是否加载过数据
				balanceAmount: "0.00", //上期未还本金
				termInterest: "0.00", //上期未还利息
				termPenaltyInterest: "0.00", //上期逾期利息
				tradeAmount: "0.00", //本期消费金额
				bannerList: []
			},
			isAnShuoUser: false //是否是灰度用户，传入详情页，判断查询消费详情接口
		};
		this.version = this.props.getAppPlatformsDatas.sdkVersionCode || "1.0.1";
	}

	componentDidMount() {
		//上一页面直接设置跳转的tabIndex
		let { state } = this.props.location;
		//redux记录的上次的tabIndex
		const { myPage } = this.props.billReducer;
		if (state && state.tableIndex != -1) {
			//跳转前指定了tab
			this.setState(
				{
					tabIndex: state.tableIndex
				},
				() => {
					this.prepareData(state.tableIndex, false);
					this.getBannerList(state.tableIndex);
				}
			);
		} else if (myPage && myPage.tabIndex) {
			//redux中缓存了的tab
			this.setState(
				{
					tabIndex: myPage.tabIndex
				},
				() => {
					this.prepareData(myPage.tabIndex, false);
					this.getBannerList(myPage.tabIndex);
				}
			);
		} else {
			//未指定跳转tab
			this.setState(
				{
					tabIndex: 0
				},
				() => {
					this.prepareData(0, true);
					this.getBannerList(0);
				}
			);
		}
	}
	prepareData(billStatus, prev) {
		//prev:是否初始化调用
		const params = {
			url: xhfConfig.billInitInfo,
			params: {
				versionId: this.props.getAppPlatformsDatas.sdkVersionCode
			},
			_alertShow: false
		};
		Toast.loading();
		yhTools.request(params).then(res => {
			Toast.hide();
			if (res.code === "0") {
				this.setState({
					isAnShuoUser: res.data.isAnShuoUser
				});
				this.props._billHomeData({ isAnShuoUser: res.data.isAnShuoUser });
				let { hasOutOfAccountBO, notOutOfAccountBO } = res.data;
				if (
					hasOutOfAccountBO.billTotalAmount == "0.00" &&
					notOutOfAccountBO.billTotalAmount != "0.00" &&
					prev
				) {
					//若本期无应还，下期有待还,并且为首次进入页面，默认展示下期待还；
					this.setState({
						pageData: {
							...notOutOfAccountBO,
							transactionList: notOutOfAccountBO.transactionList || []
						},
						tabIndex: 1,
						isLoaded: true
					});
				} else if (billStatus == "0") {
					//本期应还
					this.setState({
						pageData: {
							...hasOutOfAccountBO,
							transactionList: hasOutOfAccountBO.transactionList || []
						},
						isLoaded: true
					});
				} else {
					//下期待还
					this.setState({
						pageData: {
							...notOutOfAccountBO,
							transactionList: notOutOfAccountBO.transactionList || []
						},
						isLoaded: true
					});
				}
			} else {
				Toast.info(res.message, 2);
			}
		});
	}
	/**获取banner */
	getBannerList(tableIndex) {
		const params = {
			url: InterfaceG.getChannelBannerList,
			params: {
				pageType:
					tableIndex == 0 ? "XHF_MY_BILL_PAGE" : "XHF_MY_BILL_NEXT_ISSUE_PAGE",
				productNo: "601"
			},
			_alertShow: false
		};
		yhTools.request(params).then(res => {
			const { code, data = {} } = res;
			if (code == "0") {
				let bannerList = [];
				let bannerObj = data["1"] && data["1"].length > 0 ? data["1"]["0"] : {};
				bannerObj["link"] = bannerObj.linkUrl;
				bannerList.push(bannerObj);
				this.setState({
					bannerList
				});
			}
		});
	}
	tabSelectCallback(tabIndex) {
		if (tabIndex === "bill") {
			this.props.history.push({
				pathname: "/billHistory"
			});
		} else {
			this.setState({
				tabIndex,
				isLoaded: false //是否加载过数据
			});
			this.prepareData(tabIndex, false);
			this.getBannerList(tabIndex);
			// redux中存入当前高亮选择的tab
			this.props._billHomeData({ myPage: { tabIndex } });
		}
	}
	// 点击列表
	cellSelectCallback(cellData) {
		this.props._billDetail({
			billDetail: {
				backPath: "#/billHome",
				tradeNo: cellData.tradeNo,
				tradeType: cellData.type
			}
		});
		this.props.history.push({
			pathname: "/billDetail",
			params: {
				backPath: "#/billHome",
				tradeNo: cellData.tradeNo,
				tradeType: cellData.type
			}
		});
	}

	//去还款
	goToRepayment = i => {
		let billAmount; //还款金额
		if (i == "1") {
			let that = this;
			//最低还款
			const params = {
				url: InterfaceG.xhfMinRepaymentBtn,
				params: {},
				_alertShow: false
			};
			yhTools.request(params).then(res => {
				if (res.code == 0) {
					//继续最低还款
					billAmount = that.state.pageData.minAmount;
					that.payMoney(i, billAmount);
				} else if (res.code === "100060") {
					//本期账单不支持最低还款，点击继续还款，走全额还款
					modalAlert("提示", res.message, [
						{
							text: "取消",
							onPress: () => {}
						},
						{
							text: "继续还款",
							onPress: () => {
								billAmount = that.state.pageData.inFullAmount;
								that.payMoney(i, billAmount);
							}
						}
					]);
				} else if (res.message) {
					modalAlert("提示", res.message, [
						{
							text: "确定",
							onPress: () => {}
						}
					]);
				}
			});
		} else if (i == "2") {
			//全额还款
			billAmount = this.state.pageData.inFullAmount;
			this.payMoney(i, billAmount);
		} else if (i == "3") {
			//提前还款
			billAmount = this.state.pageData.billTotalAmount;
			this.payMoney(i, billAmount);
		}
	};
	payMoney = (i, billAmount) => {
		let obj = {
			fromType: "XHF",
			backPath: "billHome",
			billNo: this.state.pageData.billNo,
			billAmount: billAmount,
			type: i, // 1:最低还款、2:立即还款,3:提前还款
			rtnDate: this.state.pageData.rtnDate,
			showAlipayRepaymentBtn: this.state.pageData.showAlipayRepaymentBtn,
			repayMark: i == "3" ? 1 : i == "2" ? 2 : null, //未出账：提前还款传1/已出账：全额还款传2
			unAccountAmount: i == "3" ? this.state.pageData.unAccountAmount : null, //提前还款才需要传这个
			unRepayAmount: i == "3" ? this.state.pageData.unRepayAmount : null //提前还款才需要传这个
		};
		this.props.history.push({
			pathname: `/xhfRepaymentPage/${JSON.stringify(obj)}`
		});
	};
	onWrapTouchStart = e => {
		// fix touch to scroll background page on iOS
		if (!/iPhone|iPod|iPad/i.test(navigator.userAgent)) {
			return;
		}
		const pNode = closest(e.target, ".am-modal-content");
		if (!pNode) {
			e.preventDefault();
		}
	};
	accSub(num1, num2) {
		let r1, r2, m, n;
		try {
			r1 = num1.split(".")[1].length;
		} catch (e) {
			r1 = 0;
		}
		try {
			r2 = num2.split(".")[1].length;
		} catch (e) {
			r2 = 0;
		}
		m = Math.pow(10, Math.max(r1, r2));
		n = r1 >= r2 ? r1 : r2;
		return (Math.round(num1 * m - num2 * m) / m).toFixed(n);
	}
	//查看更多
	handleSeeMore = () => {
		const { pageData } = this.state;
		const { transactionList } = pageData;
		this.props._billList({
			transactionList
		});
		this.props.history.push({
			pathname: `/billList`,
			param: {
				transactionList
			}
		});
	};
	render() {
		const { pageData, isLoaded, tabIndex, bannerList } = this.state;
		const { transactionList } = pageData;
		const showList = transactionList.slice(0, 3);
		const _pageParams = {
			header: {
				title: "我的账单",
				rightButt: "历史账单",
				rightButtCallBack: () => {
					this.props.history.push({
						pathname: "/billHistory"
					});
				},
				goBackAction: () => {
					// 如果是钱包进来还款的
					let isfromQb = sessionStorage.getItem("xhqbGoBill");
					if (isfromQb == 1) {
						this.props.history.push("/xhqbIndex");
					} else {
						this.props.history.push("/xhfHomeCredit");
					}
					sessionStorage.removeItem("xhqbGoBill");
				}
			},
			history: this.props.history,
			cacheLifecycles: this.props.cacheLifecycles
		};
		return (
			<MainLayout pageParams={_pageParams}>
				<div className="bill-home-page">
					<div className="bill-home-container">
						<div className="bill-info-box">
							<div className="bill-tab-top">
								<span
									className={tabIndex == 0 ? "lable select-lable" : "lable"}
									onClick={() => this.tabSelectCallback(0)}
								>
									本期应还
								</span>
								<span className="shu"></span>
								<span
									className={tabIndex == 1 ? "lable select-lable" : "lable"}
									onClick={() => this.tabSelectCallback(1)}
								>
									下期待还
								</span>
							</div>
							{/* 本期应还 */}
							{tabIndex == 0 && (
								<div className="bill-info-bot-left">
									<div className="bot-item">
										<p className="bot-title">
											剩余应还(元)
											{pageData.billStatus == "4" && (
												<span className="yuqi-tip">已逾期</span>
											)}
											{pageData.billStatus == "5" && (
												<span className="yuqi-tip">还款中</span>
											)}
											{pageData.billStatus == "6" && (
												<span className="zuidi-tip">已还最低</span>
											)}
										</p>
										<p className="bot-number">
											{Number(pageData.balanceAmount) > 0
												? pageData.balanceAmount
												: Number(pageData.rtnPrincipal) > 0
												? "本期已结清"
												: "本期无应还"}
										</p>
										<p className="bot-desc">
											本期应还{" "}
											{pageData.balanceAmount ? pageData.balanceAmount : "0.00"}
											元
											{pageData.tradeAmount &&
												(pageData.termAmount != "0.00" ||
													pageData.termInterest != "0.00" ||
													pageData.tradeAmount != "0.00") && (
													<img
														src={questionLine}
														alt=""
														onClick={() => {
															this.setState({ modal1: true });
														}}
													/>
												)}
										</p>
									</div>
									<div className="bot-item">
										<p className="bot-title">本期已还(元)</p>
										<p className="bot-number">
											{pageData.rtnPrincipal ? pageData.rtnPrincipal : "0.00"}
										</p>
										{/* 剩余应还金额大于0，展示最后还款日 */}
										{pageData.balanceAmount > 0 && (
											<p className="bot-desc">最后还款日 {pageData.rtnDate}</p>
										)}
									</div>
								</div>
							)}
							{/* 下期待还 */}
							{tabIndex == 1 && (
								<div className="bill-info-bot-right">
									<div className="bot-item">
										<p className="bot-title">待还款金额(元)</p>
										<p className="bot-number">{pageData.onHalfAngle}</p>
										<p className="bot-desc">
											总待还 ¥{pageData.billTotalAmount}
											<img
												src={questionLine}
												alt=""
												onClick={() => {
													this.setState({ modal1: true });
												}}
											/>
										</p>
									</div>
									<div className="bot-item">
										<p className="bot-title">已还金额(元)</p>
										<p className="bot-number">{pageData.rtnPrincipal}</p>
										<div>
											{pageData.billdate && (
												<p className="bot-desc">{pageData.billdate}出账</p>
											)}
											{pageData.rtnDate && (
												<p className="bot-desc">{pageData.rtnDate}前还款</p>
											)}
										</div>
									</div>
								</div>
							)}
							{/* 选择本期应还时，展示下方按钮 */}
							{tabIndex == 0 && (
								<div className="bill-btns">
									{/* 展示最低还款和还款按钮 */}
									{pageData.minRtnBtnShow && pageData.paymentButton && (
										<Fragment>
											<div
												className="btn"
												onClick={this.goToRepayment.bind(this, 1)}
											>
												最低还款
											</div>
											<div
												className="btn"
												onClick={this.goToRepayment.bind(this, 2)}
											>
												还&nbsp;&nbsp;款
												{pageData.showAlipayRepaymentBtn &&
													yhTools.isSupportAlipay(this.version) && (
														<span className="btn-tip">支付宝</span>
													)}
											</div>
										</Fragment>
									)}
									{/* 只展示还款 */}
									{!pageData.minRtnBtnShow && pageData.paymentButton && (
										<div
											className="one-btn"
											onClick={this.goToRepayment.bind(this, 2)}
										>
											还&nbsp;&nbsp;款
											{pageData.showAlipayRepaymentBtn &&
												yhTools.isSupportAlipay(this.version) && (
													<span className="one-btn-tip">支付宝</span>
												)}
										</div>
									)}
								</div>
							)}
							{/* 选择下期时，展示下方按钮 */}
							{tabIndex == 1 && pageData.prepaymentButton && (
								<div className="bill-btns">
									{/* 判断是否展示最低还款按钮 */}
									<div
										className="one-btn"
										onClick={this.goToRepayment.bind(this, 3)}
									>
										提&nbsp;前&nbsp;还&nbsp;款
										{pageData.showAlipayRepaymentBtn &&
											yhTools.isSupportAlipay(this.version) && (
												<span className="one-btn-tip">支付宝</span>
											)}
									</div>
								</div>
							)}
							{/* <p className="huank-time">还款时间：06:00 - 23:00</p> */}
						</div>
						{/* 本月明细 */}
						{!!transactionList.length && (
							<div style={{ paddingBottom: "2rem" }}>
								<div className="title-box">
									<span className="title">本月明细</span>
									<span className="more" onClick={this.handleSeeMore}>
										查看更多 >
									</span>
								</div>
								{showList.map((item, index) => {
									return (
										<div key={index}>
											<BillTableCell
												cellData={item}
												cellSelectCallback={this.cellSelectCallback.bind(this)}
											></BillTableCell>
										</div>
									);
								})}
							</div>
						)}
						{showList.length <= 0 && isLoaded && (
							<div>
								<div className="title-box">
									<span className="title">本月明细</span>
									<span className="more" onClick={this.handleSeeMore}>
										查看更多 >
									</span>
								</div>
								<p className="no-remind">暂无消费记录</p>
							</div>
						)}
						<Banner bannerList={bannerList} history={this.props.history} />
					</div>
					<Modal
						visible={this.state.modal1}
						transparent
						maskClosable={false}
						onClose={() => {
							this.setState({ modal1: false });
						}}
						title="账单金额明细"
						footer={[
							{
								text: "我知道了",
								onPress: () => {
									this.setState({ modal1: false });
								}
							}
						]}
						wrapProps={{ onTouchStart: this.onWrapTouchStart }}
					>
						<div className="modal-jine">
							{/* 本期应还 */}
							{tabIndex == 0 && (
								<Fragment>
									{pageData.termAmount && (
										<p>
											<span className="title">上期未还本金：</span>
											<span className="num">{pageData.termAmount}</span>
										</p>
									)}
									{pageData.termInterest && (
										<p>
											<span className="title">上期未还利息：</span>
											<span className="num">{pageData.termInterest}</span>
										</p>
									)}
									{pageData.tradeAmount && (
										<p>
											<span className="title">本期消费金额：</span>
											<span className="num">{pageData.tradeAmount}</span>
										</p>
									)}
								</Fragment>
							)}
							{/* 下期待还 */}
							{tabIndex == 1 && (
								<Fragment>
									{pageData.termInterest && (
										<p>
											<span className="title">上期产生利息：</span>
											<span className="num">{pageData.termInterest}</span>
										</p>
									)}
									{pageData.tradeAmount && (
										<p>
											<span className="title">本期消费金额：</span>
											<span className="num">{pageData.tradeAmount}</span>
										</p>
									)}
								</Fragment>
							)}
						</div>
					</Modal>
				</div>
			</MainLayout>
		);
	}
}

function mapStateToProps(state) {
	return state;
}

function mapDispatchToProps(dispatch) {
	return {
		_billDetail: data => {
			dispatch(BillDetailData(data));
		},
		_billList: data => {
			dispatch(BillListData(data));
		},
		_getAppPlatformsDatas: options => {
			// 同步数据
			dispatch(getAppPlatformsDatas(options));
		},
		_billHomeData: options => {
			//存入redux
			dispatch(BillHomeData(options));
		},
		_setUserType: options => {
			dispatch(setUserType(options));
		},
		_setLoanData: opntions => {
			dispatch(getLoanData(opntions));
		}
	};
}

export default connect(mapStateToProps, mapDispatchToProps)(BillHomePage);
